#include "my_header.h"
#include "analysis.h"
#include "epoll.h"
#include "dirStack.h"
#include"threadPool.h"
#include"sendMsg.h"
void *threadFunc(void*argc)
{   
    threadPool_t*pthreadPool=(threadPool_t*)argc;
    Canalysis_t command;
    while(1){
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize==0&&pthreadPool->exitFlag==0){
        {
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
            DEBUG_PRINT("I am a worker,I am in condtion wait\n");
        }
        if(pthreadPool->exitFlag==1){
            DEBUG_PRINT("worker is going to exit\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            break;
        }
            bzero(&command,sizeof(command));
            memcpy(&command,pthreadPool->command,sizeof(command));

            int netfd=pthreadPool->taskQueue.pFront->netfd;
            pthread_mutex_unlock(&pthreadPool->mutex);
        //将netfd
            DEBUG_PRINT("worke got a netfd=%d\n",netfd);
            deQueue(&pthreadPool->taskQueue);
            int sret =pthreadPool->command->flag;
            if(sret==6){
                  LOG("The client request download a file");
                  DEBUG_PRINT("worker recv a request for dowload a file\n");
                  DEBUG_PRINT("filename=%s\n",command.lastname);
                  //发文件
                  DEBUG_PRINT("current path: %s\n", getcwd(NULL, 0));
                  //把命令的绝对路径传入finalPath
                  char finalPath[1024]={0};
                  sprintf(finalPath,"%s",command.result);
                  sret=getsFile(finalPath,&command,netfd);
                  if(sret!=0){
                      DEBUG_PRINT("transfile fail\n");
                      continue;
                  }   
                  DEBUG_PRINT("transfile success\n");
                  sendMsg(netfd,"gets success\n");
            }
            else if(sret==7){
                  //收文件
                  LOG("The client request save a file");
                  DEBUG_PRINT("worker recv a request for save file\n");
                  DEBUG_PRINT("filename=%s\n",command.lastname);
                  char finalPath[1024]={0};
                  sprintf(finalPath,"%s",command.result);
                  sret=putsFile(finalPath,&command,netfd);
                  if(sret!=0){
                      DEBUG_PRINT("recvfile fail\n");
                      continue;
                  }
                  DEBUG_PRINT("transfile success\n");
                 sendMsg(netfd,"puts success\n");
              }
        }
    }

}

int makeWorker(threadPool_t*pthreadPool){
    for(int i=0;i<pthreadPool->tidArr.workerNum;++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}


